package com.woniuxy.secondkill.configuration;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhangyong
 * @Date 2021/8/13 0013上午 10:45
 */
@Configuration
public class RabbitMQConfiguration {
    //死信交换机、路由
    public static final String DEAD_EXCHANGE = "kill_dead_exchange";
    public static final String DEAD_ROUTING_KEY = "kill_dead_route_key";
    //业务交换机、路由
    public static final String BUSINESS_EXCHANGE = "business_exchange";
    public static final String BUSINESS_ROUTING_KEY = "business";
    //队列名
    public static final String BUSINESS_QUEUE = "business_queue";
    public static final String DEAD_QUEUE = "kill_dead_queue";

    /**
     * 业务队列、交换机
     */
    @Bean
    public Queue businessQueue() {
        //指定初始化参数
        Map<String, Object> map = new HashMap<>();
        //死信交换机
        map.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        //死信路由
        map.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);
        //长度：在某个时刻最多能同时放10个，不是最多只能接收10个
        map.put("x-max=length", 10);
        //指定消息溢出之后操作
        //drop-head 删除消息，消息会变成死信
        //reject-publish  拒绝接收消息  无法成为死信
        map.put("x-overflow", "drop-head");
        //创建
        return new Queue(BUSINESS_QUEUE, false, false, false, map);
    }

    //业务交换机
    @Bean
    public DirectExchange businessExchange() {
        return new DirectExchange(BUSINESS_EXCHANGE);
    }

    //绑定
    @Bean
    public Binding bindingBusinessQueueToBusinessExchange(Queue businessQueue, DirectExchange businessExchange) {
        return BindingBuilder.bind(businessQueue).to(businessExchange).with(BUSINESS_ROUTING_KEY);
    }

    /**
     * 死信队列、交换机
     */
    //队列
    @Bean
    public Queue killDeadQueue() {
        return new Queue(DEAD_QUEUE);
    }

    //交换机
    @Bean
    public DirectExchange killDeadExchange() {
        return new DirectExchange(DEAD_EXCHANGE);
    }

    //队列绑定交换机
    @Bean
    public Binding bindingKillQueueToKillDeadExchange(Queue killDeadQueue, DirectExchange killDeadExchange) {
        return BindingBuilder.bind(killDeadQueue).to(killDeadExchange).with(DEAD_ROUTING_KEY);
    }
}
